<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */
declare (strict_types = 1);

namespace app\index\model;

use app\SearchModel;
use think\Exception;
use think\facade\Db;
use app\command\Group;

class GroupCommodity extends BaseModel
{
    protected $globalScope = ['mallId'];

    public function commodity()
    {
        return $this->hasOne(Commodity::class, 'id', 'commodity_id')->bind(['name']);
    }

    public function sku()
    {
        return $this->hasMany(GroupCommoditySku::class, 'gc_id', 'id');
    }

    public function group()
    {
        return $this->belongsTo(Group::class, 'group_id', 'id');
    }

    /**
     * 开团/参团
     * @param $commodity_id
     * @param $sku_id
     * @param $user
     * @param int $collage_id
     * @param int $group_level
     * @param int $num
     * @return GroupCommodity|array|\think\Model|null
     * @throws
     */
    public static function check($commodity_id, $sku_id, $user, $collage_id = 0, $group_level = 0, $num = 1)
    {
        $gc = GroupCommodity::where('commodity_id', $commodity_id)
            ->field('*')
            ->where('status', 1)
            ->find();
        if (empty($gc) || $gc['end_time'] < date("Y-m-d H:i:s", time())) {
            throw new Exception("拼团已结束！", HTTP_NOTACCEPT);
        }
        $gc = $gc->toArray();
        unset($gc['end_time']);
        if ($sku_id > 0) {
            $sku = GroupCommoditySku::where('gc_id', $gc['id'])
                ->where('sku_id', $sku_id)
                ->find()
                ->toArray();
            unset($sku['id']);
            $sku['use_coupon'] = $gc['use_coupon'];
            $sku['use_agent'] = $gc['use_agent'];
            $gc = array_merge($gc, $sku);
        }
        // 拼团库存
        if ($gc['activity_stock'] <= 0) {
            throw new Exception("拼团库存紧张！", HTTP_NOTACCEPT);
        }
        unset($gc['activity_stock']);
        // 限购
        $limit_type = json_decode($gc['limit_type']);
        if ($limit_type[$limit_type[0]] != 0) {
            $where = [
                'o.user_id' => $user['id'],
                'c.gc_id' => $gc['id'],
                'c.commodity_id' => $commodity_id,
                'c.status' => ['in', '2,3,4,5,7,8,9,10']//订单状态: 1-待支付 2-待发货 3-已发货 4-已完结 5-已评价   6-删除 7-已收货 8-维权中 9-已维权 10-维权驳回 11-已关闭
            ];
            if ($sku_id > 0) {
                array_push($where, ['c.sku_id' => $sku_id]);
            }

            if ($limit_type[0] == 1) {
                $count = OrderCommodity::alias('c')
                    ->join('order o', 'c.order_id = o.id', 'LEFT')
                    ->where($where)
                    ->count('c.count') + $num;
                $limit = $limit_type[1] - $count;
            } else {
                $count = OrderCommodity::alias('c')
                    ->join('order o', 'c.order_id = o.id', 'LEFT')
                    ->where($where)
                    ->whereTime('o.create_time', 'between', [
                    date('Y-m-d H:i:s',strtotime(date('Y-m-d'))), strtotime(date('Y-m-d',strtotime('+1 day')))
                ])->count('c.count') + $num;
                $limit = $limit_type[2] - $count;
            }
            if ($limit < 0) {
                throw new Exception("拼团数额超出上线！", HTTP_NOTACCEPT);
            }
        }
        unset($gc['limit_type']);

        // 参团
        if ($collage_id > 0) {
            $group_level = self::checkJoin($commodity_id, $sku_id, $user['id'], $collage_id);
            $gc['collage_id'] = $collage_id;
            $gc['leader_price'] = -1;

            $price = json_decode($gc['activity_price'], true);
            if (is_array($price)) {
                $gc['activity_price'] = $price[$group_level];
                $gc['id'] .=  ",".$group_level;
            }
        } else {
            // 拼团价
            $price = json_decode($gc['activity_price'], true);
            if (is_array($price)) {
                $gc['activity_price'] = $price[$group_level];
                $gc['id'] .=  ",".$group_level;
            }
        }
        
        return $gc;
    }

    /**
     * 参团
     * @param $commodity_id
     * @param $sku_id
     * @param $user_id
     * @param $collage_id
     * @return |null
     * @throws
     */
    public static function checkJoin($commodity_id, $sku_id, $user_id, $collage_id)
    {
        $collage = Collage::find($collage_id);
        $head = OrderCommodity::find($collage['oc_id']);

        if (is_null($collage) || is_null($head)) {
            throw new Exception("该团已截止！", HTTP_NOTACCEPT);
        }
        if ($head->getOrder()->find()['user_id'] == $user_id) {
            throw new Exception("不能参与自己开的团！", HTTP_NOTACCEPT);
        }
        $is_join = CollageItem::where([
            'user_id' => $user_id,
            'collage_id' => $collage_id
        ])->find();
        if (!empty($is_join)) {
            throw new Exception("该团只能参与一次！", HTTP_NOTACCEPT);
        }
        // 是否达到成团人数
        $where = [
            'commodity_id' => $commodity_id,
            'sku_id' => $sku_id,
            'collage_id' => $collage_id,
            'gc_id' => $head['gc_id']
        ];
        $num = CollageItem::where($where)->count('id');
        if ($num >= $collage['success_num']) {
            throw new Exception("该团已满！", HTTP_NOTACCEPT);
        }

        $data = explode(",", $head['gc_id']);
        if (isset($data[1])) {
            return $data[1];
        }
        return null;
    }


    /**
     * 处理拼团中
     * @param $now
     * @throws
     */
    public static function finishCollage($gc_id)
    {
        $Group = new Group();
        $Group->setCollage(date("Y-m-d H:i:s", time()), $gc_id);
    }

}
